package com.uduemc.biso.node.web.service.byfeign.impl;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uduemc.biso.core.extities.pojo.ICP35;
import com.uduemc.biso.core.utils.RedisUtil;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.core.utils.ResultUtil;
import com.uduemc.biso.node.core.backend.feign.WebBackendFeign;
import com.uduemc.biso.node.core.common.entities.SSL;
import com.uduemc.biso.node.core.common.feign.CSSLFeign;
import com.uduemc.biso.node.core.entities.HDomain;
import com.uduemc.biso.node.core.feign.HDomainFeign;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.core.utils.RestResultUtil;
import com.uduemc.biso.node.web.service.AsyncDomainService;
import com.uduemc.biso.node.web.service.byfeign.DomainService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.IDN;

@Service
public class DomainServiceImpl implements DomainService {

    @Resource
    private WebBackendFeign webBackendFeign;

    @Resource
    private HDomainFeign hDomainFeign;

    @Resource
    private GlobalProperties globalProperties;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    @Lazy
    private AsyncDomainService asyncDomainServiceImpl;

    @Resource
    private CSSLFeign cSSLFeign;

    @Override
    public HDomain getInfoByDomainName(String domainName) throws IOException {
        domainName = IDN.toUnicode(domainName);
        RestResult restResult = hDomainFeign.findByDomainName(domainName);
        HDomain hDomain = RestResultUtil.data(restResult, HDomain.class);
        return hDomain;
    }

    @Override
    public HDomain getInfoByHostDomainId(long hostId, long domainId) throws IOException {
        RestResult restResult = hDomainFeign.findDomainByHostidAndId(domainId, hostId);
        HDomain hDomain = RestResultUtil.data(restResult, HDomain.class);
        return hDomain;
    }

    @Override
    public HDomain getDefaultDataByHostId(long hostId) throws IOException {
        RestResult restResult = hDomainFeign.findDefaultDomainByHostId(hostId);
        HDomain hDomain = RestResultUtil.data(restResult, HDomain.class);
        return hDomain;
    }

    @Override
    public ICP35 getIcpDomain(String domain) throws IOException {
        RestResult restResult = webBackendFeign.getIcpDomain(domain);
        ICP35 icp35 = RestResultUtil.data(restResult, ICP35.class);
        return icp35;
    }

    @Override
    public ICP35 getCacheIcpDomain(String domain) {
        String KEY = globalProperties.getSiteRedisKey().getIcpDomainCachekey(domain);
        ICP35 icp35 = (ICP35) redisUtil.get(KEY);
        if (icp35 != null) {
            // 获取剩余时间，如果小于0.5个小时重新异步获取备案信息
            long expire = redisUtil.getExpire(KEY);
            if (expire < 1800) {
                // 异步重新获取ICP备案信息，如果已备案则缓存24小时，如果未备案则缓存2小时。
                asyncDomainServiceImpl.asyncCacheIcpDomain(domain, 3600 * 2, 3600);
            }
            return icp35;
        }
        try {
            icp35 = getIcpDomain(domain);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (icp35 != null && icp35.getResult() != -1) {
            if (icp35.getResult() == 1) {
                redisUtil.set(KEY, icp35, 3600 * 2);
            } else if (icp35.getResult() == 0) {
                redisUtil.set(KEY, icp35, 3600);
            }
        }
        return icp35;
    }

    @Override
    public ICP35 getCacheIcpDomain(HDomain hDomain) throws IOException {
        if (hDomain == null) {
            return null;
        }
        String domain = hDomain.getDomainName();
        String KEY = globalProperties.getSiteRedisKey().getIcpDomainCachekey(domain);
        ICP35 icp35 = (ICP35) redisUtil.get(KEY);
        if (icp35 != null) {
            // 获取剩余时间，如果小于0.5个小时重新异步获取备案信息
            long expire = redisUtil.getExpire(KEY);
            if (expire < 1800) {
                // 异步重新获取ICP备案信息，如果已备案则缓存24小时，如果未备案则缓存2小时。
                asyncDomainServiceImpl.asyncCacheIcpDomain(hDomain, 3600 * 24, 3600 * 2);
            }
            return icp35;
        }

        String remark = hDomain.getRemark();
        if (StrUtil.isNotBlank(remark)) {
            try {
                icp35 = objectMapper.readValue(remark, ICP35.class);
            } catch (IOException e) {
            }
        }
        if (icp35 != null) {
            if (icp35.getResult() == 1) {
                redisUtil.set(KEY, icp35, 3600 * 24);
            } else if (icp35.getResult() == 0) {
                redisUtil.set(KEY, icp35, 3600 * 2);
            }
        }
        // 异步的方式通过 api 获取到域名的 icp 后写入到数据库当中
        asyncDomainServiceImpl.asyncCacheIcpDomain(hDomain, 3600 * 24, 3600 * 2);
        return icp35;
    }

//	@Override
//	public ICP35 getCacheIcpDomain(String domain, boolean selfSystem) {
//		String KEY = globalProperties.getSiteRedisKey().getIcpDomainCachekey(domain);
//		ICP35 icp35 = (ICP35) redisUtil.get(KEY);
//		if (icp35 != null) {
//			return icp35;
//		}
//
//		if (selfSystem) {
//			try {
//				icp35 = getIcpDomain(domain);
//				if (icp35 != null && icp35.getResult() != -1) {
//					redisUtil.set(KEY, icp35, 3600 * 24 * 3);
//				}
//			} catch (IOException e) {
//			}
//			// 获取剩余时间，如果小于2个小时重新异步获取备案信息
//			long expire = redisUtil.getExpire(KEY);
//			if (expire < 3600 * 2) {
//				// 异步重新获取ICP备案信息
//				asyncDomainServiceImpl.asyncIcpDomain(domain);
//			}
//		} else {
//			HDomain hDomain = null;
//			try {
//				hDomain = getInfoByDomainName(domain);
//			} catch (IOException e1) {
//			}
//			if (hDomain != null) {
//				String remark = hDomain.getRemark();
//				if (StrUtil.isNotBlank(remark)) {
//					try {
//						icp35 = objectMapper.readValue(remark, ICP35.class);
//					} catch (IOException e) {
//					}
//				}
//				// 异步的方式通过 api 获取到域名的 icp 后写入到数据库当中
//				asyncDomainServiceImpl.asyncIcpDomain(hDomain);
//			}
//		}
//
//		return icp35;
//	}

    @Override
    public boolean sslHttps(long hostId, long domainId) throws IOException {
        RestResult restResult = cSSLFeign.infoByHostDomainId(hostId, domainId);
        SSL data = ResultUtil.data(restResult, SSL.class);
        if (data == null || data.getHssl() == null) {
            return false;
        }
        Short httpsOnly = data.getHssl().getHttpsOnly();
        if (httpsOnly == null) {
            return false;
        }
        if (httpsOnly.shortValue() == (short) 1) {
            return true;
        }
        return false;
    }

    @Override
    public HDomain updateAllById(HDomain hDomain) throws IOException {
        RestResult restResult = hDomainFeign.updateAllById(hDomain);
        HDomain data = ResultUtil.data(restResult, HDomain.class);
        return data;
    }

}
